package com.heifeng.cloudshelf.mvp.show.presenter;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.heifeng.cloudshelf.R;
import com.heifeng.cloudshelf.base.BaseResponse;
import com.heifeng.cloudshelf.base.RxPresenter;
import com.heifeng.cloudshelf.dao.ShowBean;
import com.heifeng.cloudshelf.helper.MyObserver;
import com.heifeng.cloudshelf.helper.RxUtil;
import com.heifeng.cloudshelf.mvp.model.DetailImageInfo;
import com.heifeng.cloudshelf.mvp.show.adapter.ShowHomeRvAdapter;
import com.heifeng.cloudshelf.mvp.show.contract.ShowHomeActivityContract;
import com.heifeng.cloudshelf.network.NetClient;
import com.heifeng.cloudshelf.utils.LogUtils;
import com.heifeng.cloudshelf.utils.LoginErrorUtils;
import com.yarolegovich.discretescrollview.DiscreteScrollView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;

/**
 * Created by admin on 2019/9/16.
 */

public class ShowHomeActivityPresenter extends RxPresenter<ShowHomeActivityContract.View> implements ShowHomeActivityContract.Presenter, DiscreteScrollView.ScrollListener<RecyclerView.ViewHolder> {
    private List<List<DetailImageInfo>> allList = new ArrayList<>();

    private List<DetailImageInfo> list = new ArrayList<>();

    private ShowHomeRvAdapter adapter;

    private LinearLayoutManager layoutManager;

    private int pageTotal = 1;
    private int pageIndex = 1;
    private int total = 0;

    @Inject
    public ShowHomeActivityPresenter() {
    }

    @Override
    public void init() {
        if (null != mView) {
            layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
            mView.getRecyclerView().setLayoutManager(layoutManager);

            adapter = new ShowHomeRvAdapter(mContext, R.layout.layout_showhome_rv_item, list);
            adapter.setHasStableIds(true);
            ((DefaultItemAnimator) mView.getRecyclerView().getItemAnimator()).setSupportsChangeAnimations(false); // 取消动画效果
            mView.getRecyclerView().setAdapter(adapter);
        }

//        initData();
    }

    @Override
    public void getBlueprintList() {
        NetClient.getInstance().getNetApi().getBlueprintList(pageIndex + "", "15")
                .compose(RxUtil.<BaseResponse<ShowBean>>rxSchedulers())
                .subscribe(new MyObserver<BaseResponse<ShowBean>>(mContext) {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<ShowBean> baseResponse) {
                        if (0 == baseResponse.getCode()) {
                            if (null != mView) {
                                initData(baseResponse.getresult().getData());
                                int count = baseResponse.getresult().getData().size();
                                if (1 == pageIndex) {
                                    total = count;
                                } else {
                                    total += count;
                                }
                                pageTotal = baseResponse.getresult().getPageTotal();
                                mView.setListSize(pageTotal);
                            } else {
                                LoginErrorUtils.loginOut(mContext, baseResponse.getCode(), baseResponse.getmsg());
                            }
                        }
                    }
                });
    }

    @Override
    public boolean isVisBottom(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //屏幕中最后一个可见子项的position
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //当前屏幕所看到的子项个数
        int visibleItemCount = layoutManager.getChildCount();
        //当前RecyclerView的所有子项个数
        int totalItemCount = layoutManager.getItemCount();
        //RecyclerView的滑动状态
        int state = recyclerView.getScrollState();

        if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void nextPage() {
        if (pageIndex + 1 <= pageTotal) {
            pageIndex += 1;
            getBlueprintList();
        }
    }

    public void initData(List<ShowBean.DataBean> data) {//模拟初始数据
        if (1 == pageIndex) {
            list.clear();
        }
        allList.clear();

        if (null != data && data.size() > 0) {
            int count = 0;

            if (list.size() > 0) {
                DetailImageInfo detailImageInfo = list.get(list.size() - 1);

                if (null != detailImageInfo.getFirstImage()) {
                    LogUtils.e("urlImage:"+detailImageInfo.getFirstImage());
                }else{
                    LogUtils.e("urlImage null");
                }
                if (null != detailImageInfo.getSecondImage()) {
                    LogUtils.e("urlImage1:"+detailImageInfo.getSecondImage());
                }else{
                    LogUtils.e("urlImage1 null");
                }
                if (null == detailImageInfo.getFirstImage()) {
                    ShowBean.DataBean dataBean = data.get(0);
                    DetailImageInfo.ImageInfoBean urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getImage(), dataBean.getTitle(), -1, dataBean.getId());
                    detailImageInfo.setFirstImage(urlImage);
                    count = 1;
                }
                if (null == detailImageInfo.getSecondImage() && data.size() > 1) {
                    ShowBean.DataBean dataBean = null;
                    if (null != detailImageInfo.getFirstImage()) {
                        dataBean = data.get(0);
                        count = 1;
                    }else{
                        dataBean = data.get(1);
                        count = 2;
                    }
                    DetailImageInfo.ImageInfoBean urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getImage(), dataBean.getTitle(), -1, dataBean.getId());
                    detailImageInfo.setSecondImage(urlImage);
                }
            }


            DetailImageInfo.ImageInfoBean urlImage;
            DetailImageInfo.ImageInfoBean urlImage1;
            while (data.size() >= count || data.size() == count - 1) {
                urlImage = null;
                urlImage1 = null;
                if (count == data.size() - 1) {
                    ShowBean.DataBean dataBean = data.get(count);
                    urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getImage(), dataBean.getTitle(), -1, dataBean.getId());
                } else if (count < data.size()) {
                    ShowBean.DataBean dataBean = data.get(count);
                    urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getImage(), dataBean.getTitle(), -1, dataBean.getId());
                    if (count + 1 < data.size()) {
                        dataBean = data.get(count + 1);
                        urlImage1 = new DetailImageInfo.ImageInfoBean(dataBean.getImage(), dataBean.getTitle(), -1, dataBean.getId());
                    }
                } else if (data.size() < count && count - 1 < data.size()) {
                    ShowBean.DataBean dataBean = data.get(count);
                    urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getImage(), dataBean.getTitle(), -1, dataBean.getId());
                }

                if (null != urlImage) {
//                    LogUtils.e("urlImage:"+urlImage.toString());
//                    if (null != urlImage1) {
//                        LogUtils.e("urlImage1:"+urlImage1.toString());
//                    }
                    DetailImageInfo info = new DetailImageInfo(urlImage, urlImage1);
                    list.add(info);
                }
                count += 2;
            }
            adapter.notifyDataSetChanged();
        }


    }

    @Override
    public void onScroll(float scrollPosition, int currentPosition, int newPosition, @Nullable RecyclerView.ViewHolder currentHolder, @Nullable RecyclerView.ViewHolder newCurrent) {

    }

    /**
     * @param list
     * @param len
     * @return 按指定大小，分隔集合，将集合按规定个数分为n个部分
     */
    public static List<List<DetailImageInfo>> splitList(List<DetailImageInfo> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return new ArrayList<>();
        }
        List<List<DetailImageInfo>> result = new ArrayList<List<DetailImageInfo>>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<DetailImageInfo> subList = new ArrayList<>();
            subList.addAll(list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1))));
            result.add(subList);
        }
        return result;
    }
}
